<template>
  <Drawer
    placement="right"
    :closable="true"
    v-model="visible"
    width="400"
    scrollable
    @on-close="cancel"
  >
    <template #header>
      <div class="flex flex-col justify-between">
        <div class="flex items-center mb-4 gap-x-2">
          <img src="~@/assets/images/icon_discussion.jpeg" class="w-6 h-6" alt="Start icon" />
          <div class="flex flex-col gap-y-1">
            <p class="text-lg font-semibold text-black">{{ title }}</p>
          </div>
        </div>
        <div class="text-sm text-gray-500">
          {{ desc }}
        </div>
      </div>
    </template>

    <CommonCollapse title="输入" tip="输入需要添加到提示词的信息，这些信息可以被下方的提示词引用">
      <div class="panel-table">
        <div class="panel-table-header">
          <div class="name" style="width: 150px">变量名</div>
          <div class="name">变量值</div>
        </div>
        <div v-if="form" class="panel-table-list">
          <Form ref="formEl" :model="form" label-position="top">
            <div
              class="flex items-center mb-4"
              v-for="(item, index) in form.inoutlist"
              :key="index"
            >
              <div class="panel-table-item" style="width: 160px">
                <FormItem
                  :key="index"
                  :prop="'inoutlist.' + index + '.varname'"
                  :rules="{
                    required: true,
                    message: '变量名不可为空',
                    trigger: 'blur'
                  }"
                >
                  <Input
                    v-model="item.varname"
                    readonly
                    placeholder="输入引用参考值"
                    size="small"
                  />
                </FormItem>
              </div>
              <div class="panel-table-item" style="width: 100px; margin-right: 0">
                <FormItem>
                  <Select size="small" disabled v-model="item.vartype">
                    <Option v-for="item in BE_TYPE_LIST" :value="item.value" :key="item.value">
                      {{ item.label }}</Option
                    >
                  </Select>
                </FormItem>
              </div>
              <div class="panel-table-item" style="width: 180px">
                <FormItem
                  :prop="'inoutlist.' + index + '.varparam'"
                  :rules="{
                    required: true,
                    message: '变量值不可为空',
                    trigger: 'blur'
                  }"
                >
                  <Input
                    size="small"
                    v-model="item.varparam"
                    check-strictly
                    placeholder="输入或引用参考值"
                  >
                  </Input>
                </FormItem>
              </div>
            </div>
          </Form>
        </div>
      </div>
    </CommonCollapse>
    <Divider></Divider>

    <CommonCollapse title="知识库" tip="选择需要匹配的知识范围，仅从选定的知识中召回信息">
      <template #right>
        <Button type="primary" size="small" icon="md-add" @click="showModal = true"></Button>
      </template>

      <ul class="knowledge-gather">
        <li v-for="item in knowledgeList" :key="item.id">
          <div class="label">
            <img src="@/assets/images/dataset_text.png" alt="" />
            <span>{{ item.name }}</span>
          </div>

          <Button
            type="text"
            icon="ios-trash"
            @click="form.knowledgeid.splice(form.knowledgeid.indexOf(item.id), 1)"
          ></Button>
        </li>
      </ul>

      <template v-if="form.knowledgeid.length">
        <ul class="strategy-content">
          <li>
            <div class="label">
              <span>搜索策略</span>
              <Tooltip
                content="从知识库中获取知识的检索方式，不同的检索策略可以更有效地找到正确的信息，提高其生成的答案的准确性和可用性。"
                theme="light"
                placement="top"
                transfer
                max-width="400"
              >
                <Icon type="ios-alert-outline" size="16" />
              </Tooltip>
            </div>

            <Select v-model="form.segmenttag" size="small">
              <Option v-for="item in segmenttagGather" :value="item.id" :key="item.id">
                {{ item.name }}</Option
              >
            </Select>
          </li>

          <li>
            <div class="label">
              <span>最大召回数量</span>
              <Tooltip
                content="从知识库中返回给大模型的最大段落数，数值越大返回的内容越多"
                theme="light"
                placement="top"
                transfer
                max-width="400"
              >
                <Icon type="ios-alert-outline" size="16" />
              </Tooltip>
            </div>

            <Poptip
              trigger="click"
              title="请谨慎操作"
              transfer
              :disabled="true"
              :width="240"
              word-wrap
              content="太大可能导致召回段落超过Token限制，超过Token部分的低匹配段落将不会传输到大模型。"
              placement="bottom"
            >
              <Slider v-model="form.segmentmaxilength" :max="20" :marks="marks"></Slider>
            </Poptip>
          </li>

          <li>
            <div class="label">
              <span>最小匹配度</span>
              <Tooltip
                content="根据设置的匹配度选取段落返回给大模型，低于设定匹配度的内容不会被召回"
                theme="light"
                placement="top"
                transfer
                max-width="400"
              >
                <Icon type="ios-alert-outline" size="16" />
              </Tooltip>
            </div>

            <Slider
              v-model="form.minmatch"
              :min="0.01"
              :max="0.99"
              :step="0.01"
              :marks="marks1"
            ></Slider>
          </li>
        </ul>

        <ul class="checkbox-content">
          <li v-for="(item, index) in checkOptions" :key="index">
            <div class="label">
              <Checkbox v-model="form[item.key]">{{ item.name }}</Checkbox>
              <Tooltip
                v-if="item.tips"
                :content="item.tips"
                theme="light"
                placement="top"
                transfer
                max-width="400"
              >
                <Icon type="ios-alert-outline" size="16" />
              </Tooltip>
            </div>

            <p class="desc">{{ item.desc }}</p>
          </li>
        </ul>
      </template>
    </CommonCollapse>
    <Divider></Divider>

    <CommonCollapse title="输出" tip="大模型运行完成后生成的内容">
      <el-tree default-expand-all :data="form.commonoutvo">
        <template #default="{ node, data }">
          <div class="panel-table">
            <div class="flex items-center">
              <span class="text-sm">{{ data.varname }}</span>

              <div class="text-bg-normal">{{ data.vartype }}</div>
            </div>
          </div>
        </template>
      </el-tree>
    </CommonCollapse>

    <KnowledgeSelect v-model="showModal" :form="form" :skillList="skillList" multiple />
  </Drawer>
</template>
<script setup>
import { ref, computed } from 'vue'
import CommonCollapse from '@/components/CommonCollapse/index.vue'
import { dicCode } from '@/api/modules/flow'
import { myKnowledge } from '@/api/modules/knowledgeBase'

import { BE_TYPE_LIST } from '../../lib/constant'

import KnowledgeSelect from '@/components/FlowCanvas/components/dialog/KnowledgeSelect.vue'

const TYPE_OPTIONS = ['语义', '混合', '全文']

const props = defineProps({
  form: {
    type: Object,
    default: () => {}
  },
  title: {
    type: String,
    default: '输出'
  },
  desc: String
})

const emit = defineEmits(['add', 'remove', 'cancel'])

const visible = ref(false)
const showModal = ref(false)
const marks = ref({
  0: {
    style: {
      color: '#000'
    },
    label: '0'
  },
  5: {
    style: {
      'font-size': '14px'
    },
    label: 'Default'
  },
  20: {
    style: {
      color: '#000'
    },
    label: '20'
  }
})

const marks1 = ref({
  0.01: {
    style: {
      color: '#000'
    },
    label: '0.01'
  },
  0.5: {
    style: {
      'font-size': '14px'
    },
    label: 'Default'
  },
  0.99: {
    style: {
      color: '#000'
    },
    label: '0.99'
  }
})

const checkOptions = ref([
  {
    name: '查询改写',
    tips: '从知识库中获取知识的检索方式，不同的检索策略可以更有效地找到正确的信息，提高其生成的答案的准确性和可用性。',
    desc: '对输入的查询语句进行优化重构，从而能够更准确地捕捉用户意图，提升信息检索的效率',
    key: 'isselect'
  },
  {
    name: '结果重排',
    desc: '开启后用户只可以搜索用户自己上传的和开发者预置的文档，其他人上传的文档不可见',
    key: 'isresult'
  },
  {
    name: '查询改写',
    desc: '开启后用户只可以搜索用户自己上传的和开发者预置的文档，其他人上传的文档不可见',
    key: 'isonlydoc'
  }
])

const segmenttagGather = ref([])
const getSegmenttageData = () => {
  dicCode({
    data: {
      code: 'com.dic.aiflow.knowledgebase.search'
    }
  }).then(({ data }) => {
    data.shift()
    segmenttagGather.value = data
  })
}
getSegmenttageData()

const skillList = ref([])
const getKnowledgeList = async () => {
  const { data } = await myKnowledge.catePage({
    query: {
      p: 1,
      ps: 1000
    },
    data: {
      aitype: 'kb'
    }
  })
  skillList.value = data.topicList
}
getKnowledgeList()

const knowledgeList = computed(() => {
  return skillList.value.filter((item) => props.form.knowledgeid.includes(item.id))
})

// 组件的增删
const addInput = (listKey) => {
  emit('add', listKey)
}
const removeInput = (listKey, index) => {
  if (listKey == 'outputList' && index == 0) return
  emit('remove', listKey, index)
}
const init = () => {
  visible.value = true
}
const cancel = () => {
  visible.value = false
  emit('cancel')
}

defineExpose({
  init,
  knowledgeList
})
</script>
<style lang="scss" scoped>
.panel-table-header {
  align-items: center;
  display: flex;
  gap: 4px;
  padding: 0 4px;

  .name {
    width: 120px;
    margin-right: 6px;
    box-sizing: content-box;
  }
  .center {
    text-align: center;
  }
}

:deep(.ivu-form-item-error-tip){
  font-size: 12px;
}
.panel-table-item {
  height: 30px;
  margin-right: 6px;
  &.center {
    text-align: center;
  }
  &.btn {
    cursor: pointer;
    font-size: 16px;
    font-weight: bold;
    margin-left: 12px;
    height: 22px;
  }
}

.el-tree-node__content {
  margin-top: 16px;
}

.knowledge-gather {
  > li {
    display: flex;
    justify-content: space-between;
    align-items: center;
    border: 1px solid #e9ebf1;
    border-radius: 8px;
    padding: 10px;
    cursor: pointer;
    &:hover {
      background-color: #f6f6fb;
      .ivu-btn {
        display: block;
      }
    }
    &:nth-child(n + 2) {
      margin-top: 8px;
    }
    .label {
      display: flex;
      align-items: center;
      color: #0f1528d1;
      font-weight: 500;
      img {
        width: 30px;
        height: 30px;
        margin-right: 12px;
      }
    }
    :deep(.ivu-btn) {
      display: none;
      height: 30px;
      line-height: 1;
      .ivu-icon {
        font-size: 20px;
      }
    }
  }
}

.strategy-content {
  > li {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-top: 24px;
    .label {
      font-size: 12px;
      .ivu-tooltip {
        margin-left: 4px;
        cursor: pointer;
      }
    }
    .ivu-select,
    .ivu-slider {
      width: 140px;
    }
  }
}

.checkbox-content {
  margin-top: 44px;
  li {
    font-size: 12px;
    &:nth-child(n + 2) {
      margin-top: 24px;
    }
    .label {
      :deep(.ivu-checkbox-label-text) {
        margin-left: 4px;
      }
    }
    .desc {
      margin-top: 4px;
      margin-left: 24px;
    }
  }
}
</style>
